package com.tea.admin.modules.app.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tea.common.entity.app.GoodsProperty;
import com.tea.common.entity.app.dto.AdminGoodsDTO;
import com.tea.common.entity.app.dto.GoodsDTO;
import com.tea.admin.modules.app.mapper.GoodsAdminMapper;
import com.tea.admin.modules.app.mapper.GoodsPropertyAdminMapper;
import com.tea.common.common.config.property.IOProperty;
import com.tea.common.common.exception.ServiceException;
import com.tea.common.entity.GoodsStore;
import com.tea.common.mapper.GoodsStoreMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class GoodsAdminService {

    @Resource
    private GoodsAdminMapper goodsAdminMapper;
    @Resource
    private IOProperty ioProperty;
    @Resource
    private GoodsPropertyAdminMapper goodsPropertyAdminMapper;
    @Resource
    private GoodsStoreMapper goodsStoreMapper;

    /**
     * 分页条件查询
     *
     * @param pageNo   页号
     * @param pageSize 页面大小
     * @param storeId  门店ID，可为null
     * @return Page<GoodsAdmin>
     */
    public Page<AdminGoodsDTO> getGoodsAdminByPage(int pageNo, int pageSize, Long storeId) {
        Page<GoodsDTO> page = new Page<>(pageNo, pageSize);

        // 创建基本查询条件
        QueryWrapper<GoodsDTO> queryWrapper = new QueryWrapper<GoodsDTO>().orderByAsc("goods_category_name");


        // 先查询该门店关联的所有商品ID
        QueryWrapper<GoodsStore> storeQueryWrapper = new QueryWrapper<>();
        storeQueryWrapper.eq("store_id", storeId);

        List<GoodsStore> goodsStoreList = goodsStoreMapper.selectList(storeQueryWrapper);

        // 如果该门店没有关联商品，返回空结果
        if (goodsStoreList.isEmpty()) {
            return new Page<>(pageNo, pageSize);
        }

        // 提取商品ID列表
        List<Long> goodsIds = goodsStoreList.stream()
                .map(GoodsStore::getGoodsId)
                .distinct()
                .collect(toList());

        // 在查询条件中添加商品ID条件
        queryWrapper.in("id", goodsIds);


        // 执行查询
        Page<GoodsDTO> goodsDTOPage = goodsAdminMapper.selectPage(page, queryWrapper);

        List<GoodsDTO> goodsVOList = goodsDTOPage.getRecords();
        List<AdminGoodsDTO> adminGoodsDTOS = BeanUtil.copyToList(goodsVOList, AdminGoodsDTO.class);
        for (AdminGoodsDTO goods : adminGoodsDTOS) {
            // 设置商品的属性列表
            List<GoodsProperty> goodsPropertyList = goodsPropertyAdminMapper
                    .selectList(new QueryWrapper<GoodsProperty>().eq("goods_id", goods.getId()));
            goods.setGoodsPropertyList(goodsPropertyList);
            GoodsStore goodsStore = goodsStoreMapper.selectOne(new LambdaQueryWrapper<GoodsStore>()
                    .eq(GoodsStore::getGoodsId, goods.getId())
                    .eq(GoodsStore::getStoreId, storeId));
            goods.setStatus(goodsStore.getStatus());
            goods.setStoreId(goodsStore.getStoreId());
        }
        Page<AdminGoodsDTO> page1 = new Page<>(pageNo, pageSize);
        page1.setRecords(adminGoodsDTOS);
        page1.setTotal(goodsDTOPage.getTotal());
        page1.setPages(goodsDTOPage.getPages());
        return page1;
    }

    // 根据id查询商品
    public GoodsDTO getGoodsById(Integer goodsId) {
        GoodsDTO goods = goodsAdminMapper.selectById(goodsId);
        if (goods == null) {
            return null;
        }

        // 设置商品属性列表
        goods.setGoodsPropertyList(
                goodsPropertyAdminMapper
                        .selectList(new QueryWrapper<GoodsProperty>().eq("goods_id", goodsId))
        );

        // 查询商品关联的门店
        QueryWrapper<GoodsStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId);
        List<GoodsStore> goodsStores = goodsStoreMapper.selectList(queryWrapper);

        // 如果有关联的门店，设置第一个关联门店的ID
        if (!goodsStores.isEmpty()) {
            goods.setStoreId(goodsStores.get(0).getStoreId());
        }

        return goods;
    }

    // 增加
    @Transactional
    public int addGoodsAdmin(GoodsDTO goodsDTO) {
        // 插入商品信息
        int result = goodsAdminMapper.insert(goodsDTO);

        // 如果有指定门店ID，则创建商品与门店的关联
        if (goodsDTO.getStoreId() != null) {
            createGoodsStoreRelation(goodsDTO.getId(), goodsDTO.getStoreId());
        }

        return result;
    }

    // 创建商品与门店的关联
    private void createGoodsStoreRelation(Integer goodsId, Long storeId) {
        if (goodsId == null || storeId == null) {
            return;
        }

        // 检查关联是否已存在
        QueryWrapper<GoodsStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId).eq("store_id", storeId);
        if (goodsStoreMapper.selectCount(queryWrapper) > 0) {
            return; // 关联已存在，无需重复创建
        }

        // 创建新的关联
        GoodsStore goodsStore = new GoodsStore();
        goodsStore.setGoodsId(goodsId.longValue());
        goodsStore.setStoreId(storeId);
        goodsStore.setStatus(1); // 默认上架

        goodsStoreMapper.insert(goodsStore);
    }

    // 批量删除
    @Transactional
    public int deleteGoodsAdminBatchIds(List<Integer> goodsAdminIdList) {
        // 同时删除商品与门店的关联
        for (Integer goodsId : goodsAdminIdList) {
            deleteGoodsStoreRelations(goodsId);
        }

        return goodsAdminMapper.deleteBatchIds(goodsAdminIdList);
    }

    // 删除商品与门店的关联
    private void deleteGoodsStoreRelations(Integer goodsId) {
        if (goodsId == null) {
            return;
        }

        QueryWrapper<GoodsStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId);
        goodsStoreMapper.delete(queryWrapper);
    }

    // 修改
    @Transactional
    public int updateGoodsAdmin(GoodsDTO goods) {
        // 更新商品信息
        int result = goodsAdminMapper.updateById(goods);

        // 如果有指定门店ID，则更新商品与门店的关联
        if (goods.getStoreId() != null) {
            // 先删除原有的关联
            deleteGoodsStoreRelations(goods.getId());
            // 创建新的关联
            createGoodsStoreRelation(goods.getId(), goods.getStoreId());
        }

        return result;
    }

    // 修改商品的图片
    public int updateGoodsImage(Integer goodsId, MultipartFile file) throws ServiceException {
        try {
            // 检查文件是否存在
            if (file == null || file.isEmpty()) {
                throw new ServiceException("文件为空，请选择有效的图片文件");
            }

            // 检查文件大小 (放在文件保存前)
            if (file.getSize() > 1024 * 1024) {
                throw new ServiceException("文件大小超过1MB限制");
            }

            // 获取原始文件名，提取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";

            // 确保扩展名是图片类型
            if (!fileExtension.matches("\\.(jpg|jpeg|png|gif)$")) {
                throw new ServiceException("文件类型不支持，请上传jpg、jpeg、png或gif格式的图片");
            }

            // 创建目录，使用mkdirs确保多级目录都能创建
            File dir = new File(ioProperty.getImageFileRootPath());
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    throw new ServiceException("无法创建图片存储目录");
                }
            }

            // 使用商品ID和原始扩展名生成文件名
            String goodsImageName = "goodsImage-" + goodsId + fileExtension.toLowerCase();
            File destFile = new File(dir, goodsImageName);

            // 保存文件
            file.transferTo(destFile);

            // 更新数据库中的图片路径
            return goodsAdminMapper.updateImageByGoodsId(goodsId, goodsImageName);
        } catch (ServiceException se) {
            // 业务异常直接抛出
            throw se;
        } catch (Exception e) {
            // 记录详细错误日志
            log.error("商品图片上传失败: goodsId={}, 错误: {}", goodsId, e.getMessage(), e);
            throw new ServiceException("商品图片上传失败: " + e.getMessage());
        }
    }

    // 获取商品关联的门店列表
    public List<GoodsStore> getGoodsStores(Integer goodsId) {
        if (goodsId == null) {
            return List.of();
        }

        QueryWrapper<GoodsStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId);

        return goodsStoreMapper.selectList(queryWrapper);
    }


}
